package com.gopay.common.order.aop;

import java.net.InetSocketAddress;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.aspectj.lang.JoinPoint;

import com.gopay.common.constants.logging.SendType;
import com.gopay.common.constants.logging.VoType;
import com.gopay.common.domain.send.SendMessage;

/**
 * 订单通知AOP
 * 
 * @AbstractOrderAspect.java
 * @author yaobo
 * @2013-4-26 下午03:20:44 www.gopay.com.cn Inc.All rights reserved.
 */
public abstract class AbstractOrderAspect {
    private static Log logger = LogFactory.getLog(AbstractOrderAspect.class);

    /**
     * 服务端地址
     */
    protected String ip;

    /**
     * 端口
     */
    protected int port;

    /**
     * 发送系统
     */
    protected String from;

    @Resource(name = "nioSocketConnector")
    private IoConnector nioSocketConnector;

    public void doAfter(JoinPoint jp) {

        try {
            SendMessage sendMessage = SendMessage.getSendMessage();
            sendMessage.setSendType(SendType.LOG);
            sendMessage.setVoType(VoType.ORDER);
            sendMessage.setData(buildData(jp));

            ConnectFuture future = nioSocketConnector.connect(new InetSocketAddress(ip, port));
            // 同步调用
            future.awaitUninterruptibly();
            future.getSession().write(sendMessage.toString());
        } catch (Exception e) {
            logger.error("mina exception.", e);
        }
    }

    /**
     * 获取SERVICE执行方法
     * 
     * @return
     */
    protected String getProcessServiceName() {
        StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
        if (stacks == null || stacks.length < 1) {
            return "";
        }

        for (int i = stacks.length - 1; i >= 0; i--) {
            StackTraceElement stack = (StackTraceElement) stacks[i];
            if (stack.getClassName().indexOf("java.lang.Thread") >= 0) {
                continue;
            }

            if (StringUtils.indexOf(stack.getClassName(), ".service") > 0) {
                String fileName = stack.getFileName();
                // 文件名前缀
                String fileNameNoPrefix = fileName;
                if (fileName.indexOf(".") != -1) {
                    fileNameNoPrefix = fileName.substring(0, fileName.indexOf("."));
                }
                return fileNameNoPrefix + "." + stack.getMethodName();
            }
        }

        return "NO SERVICE";

    }

    /**
     * 构建发送数据
     * 
     * @param jp
     * @return
     */
    protected abstract String buildData(JoinPoint jp);

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setFrom(String from) {
        this.from = from;
    }
}
